import { defineStore } from 'pinia';
import { login, getUserInfo, logout, register } from '../api/user';
import { ElMessage } from 'element-plus';

// 定义用户响应类型
interface UserResponse {
  sessionToken: string;
  username: string;
  [key: string]: any;
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('sessionToken') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    username: localStorage.getItem('username') || '',
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  
  actions: {
    // 登录
    async loginAction(username: string, password: string) {
      try {
        const response = await login(username, password);
        const userData = response as unknown as UserResponse;
        
        this.token = userData.sessionToken;
        this.username = userData.username;
        this.userInfo = userData;
        
        localStorage.setItem('sessionToken', userData.sessionToken);
        localStorage.setItem('username', userData.username);
        localStorage.setItem('userInfo', JSON.stringify(userData));
        
        ElMessage.success('登录成功');
        return userData;
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    },
    
    // 注册
    async registerAction(username: string, password: string, email: string) {
      try {
        const response = await register(username, password, email);
        ElMessage.success('注册成功，请登录');
        return response;
      } catch (error) {
        console.error('注册失败:', error);
        throw error;
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      try {
        const response = await getUserInfo();
        const userData = response as unknown as UserResponse;
        
        this.userInfo = userData;
        localStorage.setItem('userInfo', JSON.stringify(userData));
        return userData;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    },
    
    // 退出登录
    async logoutAction() {
      try {
        await logout();
        this.resetState();
        ElMessage.success('已退出登录');
      } catch (error) {
        console.error('退出登录失败:', error);
        // 即使退出失败，也清除本地状态
        this.resetState();
      }
    },
    
    // 重置状态
    resetState() {
      this.token = '';
      this.userInfo = {};
      this.username = '';
      localStorage.removeItem('sessionToken');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('username');
    }
  }
}); 